import { defineStore } from 'pinia'
import { api } from '@/utils/api'

export const useUsersStore = defineStore('users', {
  state: () => ({
    users: [],
    pagination: {
      currentPage: 1,
      totalPages: 0,
      totalItems: 0,
      itemsPerPage: 10
    },
    loading: false,
    filters: {
      email: '',
      status: '' // '', 'enabled', 'disabled'
    }
  }),

  actions: {
    async fetchUsers(params = {}) {
      this.loading = true
      try {
        const query = {
          page: params.page || this.pagination.currentPage,
          limit: params.limit || this.pagination.itemsPerPage,
          email: params.email ?? this.filters.email,
          status: params.status ?? this.filters.status
        }
        const res = await api.users.list(query)
        this.users = res.data || []
        if (res.pagination) {
          this.pagination = {
            currentPage: res.pagination.currentPage,
            totalPages: res.pagination.totalPages,
            totalItems: res.pagination.totalItems,
            itemsPerPage: res.pagination.itemsPerPage
          }
        }
      } finally {
        this.loading = false
      }
    },

    async createUser(payload) {
      const res = await api.users.create(payload)
      return res.data
    },

    async updateUser(id, payload) {
      const res = await api.users.update(id, payload)
      return res.data
    },

    async updateStatus(id, isActive) {
      const res = await api.users.updateStatus(id, isActive)
      return res.data
    },

    async resetPassword(id, newPassword) {
      await api.users.resetPassword(id, newPassword)
    },

    async deleteUser(id) {
      await api.users.delete(id)
    }
  }
})


